package com.servlet.adminaction;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.database.connection.DatabaseConnection;

@WebServlet("/DeleteUpdate")
public class DeleteUpdateUser extends HttpServlet{
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String btnSubmit = req.getParameter("btnChange");
		String userName = req.getParameter("txtUserName");
		String password = req.getParameter("txtPassword");
		String type = req.getParameter("txtType");
		String registeredDate = req.getParameter("txtRegisteredDate");
		
		Connection conn = null;
		PreparedStatement stmt = null;
		String deleteSQL = "delete from user where UserName = ?";
		String updateSQL = "update user set "
				+ "Password = ?, Type = ?, RegisteredDate = ?"
				+ "where UserName = ?";
		try {
			conn = DatabaseConnection.getConnection();
			if(btnSubmit.equals("Delete")) {
				stmt = conn.prepareStatement(deleteSQL);
				stmt.setString(1, userName);
				stmt.executeUpdate();
				req.setAttribute("changeMessage", "Deleted one row from user.");
				req.getRequestDispatcher("/ListAllUser").forward(req, resp);
			}
			else if (btnSubmit.equals("Update")) {
				stmt = conn.prepareStatement(updateSQL);
				stmt.setString(1, password);
				stmt.setString(2, type);
				stmt.setString(3, registeredDate);
				stmt.setString(4, userName);
				stmt.executeUpdate();
				req.setAttribute("changeMessage", "Updated one row from user.");
				req.getRequestDispatcher("/ListAllUser").forward(req, resp);
			}
			stmt.close();
			conn.close();
		} catch (SQLException se) {
			se.printStackTrace();
		}
	}
}
